package com.maple.springmvc;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.ContextLoader;

import com.maple.judegement.Judgement;

public class Download {

	public static final String UPLOAD_PATH="";
	//spring mvc下载文件
	public String getRootFolderPath() throws FileNotFoundException, IOException{
		 String propPath= ContextLoader.getCurrentWebApplicationContext().getServletContext().getRealPath("/WEB-INF/spring/config.properties") ;
		 Properties props=new Properties();
		 props.load(new FileInputStream(propPath));
		
		String rootFolderPath=props.getProperty(UPLOAD_PATH);//+"/"+src;
		 return rootFolderPath;
	}
			
	/**
	 * @param folderPath  文件夹的路径，例如：image,doc/xls
	 * @param resource    文件在服务器上的名字，例如 97979798792349djkfsjkldf.png
	 * @param originalName    文件本来的名字，例如 汇总.xls
	 * @throws Exception 
	 */	
	@RequestMapping("download")  
	public void download(HttpServletResponse resp,@RequestParam(required=false) String folderPath,@RequestParam String resource,@RequestParam(required=false) String originalName) throws IOException {  
		
		String rootFolderPath=getRootFolderPath();
		String filePath=rootFolderPath;
		if(Judgement.isAvailable(folderPath))
			filePath+="/"+folderPath;
		if(Judgement.isAvailable(resource))
			filePath+="/"+resource;
		File file=new File(filePath);
		
		System.out.println(filePath);
	    OutputStream os = resp.getOutputStream();  
	    try {  
	    	resp.reset();  
	    	String filename=resource;
	    	if(Judgement.isAvailable(originalName))
	    	{
	    		filename=originalName;
	    	}
	    	resp.setHeader("Content-Disposition", "attachment; filename="+filename);  
	    	resp.setContentType("application/octet-stream; charset=utf-8");  
	        os.write(FileUtils.readFileToByteArray(file));  
	        os.flush();  
	    } finally {  
	        if (os != null) {  
	            os.close();  
	        }  
	    }  
	} 


}
